<template>
	<tm-app ref="app" :bgStyle="bgStyle">
	  <view
		style="width: 100%; max-width: 900rpx; height: 100vh; margin: 0 auto"
		:style="bgStyle"
	  >
		<view class="bgImg" />
		<view v-if="formType == 0" style="z-index: 1">
		  <tm-form
			ref="form"
			:modelValue="loginForm"
			@submit="confirm"
			:label-width="0"
			:margin="[120, 0]"
			:padding="[0, 0]"
			transprent
			:border="false"
		  >
			<tm-form-item
			  :showTopErrorGap="false"
			  field="owner_name"
			  :margin="[0, 0]"
			  required
			  :rules="[
		  { required: true, message: '请输入姓名', validator: (val: any) => val.length > 0 }
	  ]"
			>
			  <tm-input
				fontColor="white"
				placeholderStyle="color:#e0e0e0"
				focusColor="orange"
				placeholder="业主姓名"
				v-model.lazy="loginForm.owner_name"
				:border="2"
				:transprent="true"
				:showBottomBotder="false"
			  >
			  </tm-input>
			</tm-form-item>
			<tm-form-item
			  :showTopErrorGap="false"
			  field="owner_phone"
			  :margin="[0, 0]"
			  required
			  :rules="[
		  { required: true, message: '请输入正确的手机号', validator: (val: any) => proxy.tm.u.isPhone(val) }
	  ]"
			>
			  <tm-input
				fontColor="white"
				placeholderStyle="color:#e0e0e0"
				focusColor="orange"
				placeholder="电话"
				v-model.lazy="loginForm.owner_phone"
				:border="2"
				:transprent="true"
				:showBottomBotder="false"
			  >
			  </tm-input>
			</tm-form-item>
			<tm-form-item
			  :showTopErrorGap="false"
			  field="owner_id_number"
			  :margin="[0, 0]"
			  required
			  :rules="[
		  { required: true, message: '不能为空', validator: (val: any) => val.length > 0 }
	  ]"
			>
			  <tm-input
				fontColor="white"
				placeholderStyle="color:#e0e0e0"
				focusColor="orange"
				placeholder="身份证后六位"
				v-model.lazy="loginForm.owner_id_number"
				:border="2"
				:transprent="true"
				:showBottomBotder="false"
			  >
			  </tm-input>
			</tm-form-item>
			<!-- <tm-form-item :margin="[0, 0]"> -->
			<view class="flex flex-row">
			  <view class="flex-1 mr-32">
				<tm-button
				  :linear-color="['#ffd700', '#ffa500']"
				  linear="bottom"
				  :round="10"
				  :margin="[0, 0]"
				  fontColor="white"
				  form-type="submit"
				  label="业主身份验证"
				  block
				></tm-button>
			  </view>
			  <view class="flex-1">
				<tm-button
				  @click="showTips = true"
				  :linear-color="['#ffd700', '#ffa500']"
				  linear="bottom"
				  :round="10"
				  :margin="[0, 0]"
				  fontColor="white"
				  label="规则"
				  block
				></tm-button>
			  </view>
			</view>
		  </tm-form>
		</view>
		<view v-else-if="formType == 1 || formType == 2" style="z-index: 1">
		  <tm-form
			ref="formSub"
			:modelValue="loginForm"
			@submit="subConfirm"
			:label-width="0"
			:margin="[120, 0]"
			:padding="[0, 0]"
			transprent
			:border="false"
		  >
			<tm-form-item
			  :margin="[0, 0]"
			  :showTopErrorGap="false"
			  required
			  field="date"
			  :rules="[{ required: true, message: '请选择日期', validator: (val: any) => val.length > 0 }]"
			>
			  <e-select
				:search="false"
				v-model="loginForm.date"
				:props="dateProps"
				:options="optionsDate"
				placeholder="选择日期"
				@change="dateChange"
			  ></e-select>
			</tm-form-item>
			<tm-form-item
			  :showTopErrorGap="false"
			  field="tId"
			  :margin="[0, 0]"
			  required
			  :rules="[
		  { required: true, message: '请选择时间段', validator: (val: any) => val.length > 0 }
	  ]"
			>
			  <e-select
				:search="false"
				emptyTips="该时间段已约满"
				v-model="loginForm.tId"
				:options="optionsTime[loginForm.date]"
				:props="timeProps"
				placeholder="选择时间段"
				@change="TimeChange"
			  ></e-select>
			</tm-form-item>
			<tm-form-item
			  :showTopErrorGap="false"
			  field="owner_number"
			  :margin="[0, 0]"
			  required
			  :rules="[
		  { required: true, message: '请输入正确的人数', validator: (val: any) => /^[1-9]\d*$/.test(val) }
	  ]"
			>
			  <tm-input
				fontColor="white"
				placeholderStyle="color:#e0e0e0"
				focusColor="orange"
				placeholder="到访人数"
				v-model.lazy="loginForm.owner_number"
				type="number"
				:maxlength="2"
				:border="2"
				:transprent="true"
				:showBottomBotder="false"
			  >
			  </tm-input>
			</tm-form-item>
			<!-- <tm-form-item :margin="[0, 0]"> -->
			<view class="flex flex-row">
			  <view class="flex-1 mr-32">
				<tm-button
				  :linear-color="['#ffd700', '#ffa500']"
				  linear="bottom"
				  :round="10"
				  :margin="[0, 0]"
				  fontColor="white"
				  form-type="submit"
				  label="提交"
				  block
				></tm-button>
			  </view>
			  <view class="flex-1">
				<tm-button
				  @click="showTips = true"
				  :linear-color="['#ffd700', '#ffa500']"
				  linear="bottom"
				  :round="10"
				  :margin="[0, 0]"
				  fontColor="white"
				  label="规则"
				  block
				></tm-button>
			  </view>
			</view>
		  </tm-form>
		</view>
		<!-- <view class="bgImg2" /> -->
		<tm-modal
		  transprent
		  hideCancel
		  :width="720"
		  :height="1200"
		  :overlayClick="false"
		  splitBtn
		  content="主体内容哦"
		  v-model:show="showTips"
		>
		  <view class="tipsCss">
			<view class="tipsContent">
			  <view style="display: flex; flex-direction: row; align-items: end">
				<span style="font-size: 48rpx">温馨提示</span>&nbsp;
				<p>WARM PROMPT</p>
			  </view>
			  <tm-divider realColor color="black"></tm-divider>
			  <scroll-view
				style="height: 820rpx; line-height: 30px"
				scroll-y
				:show-scrollbar="false"
			  >
				尊敬的龙湖·三千云锦1号地业主：
				<p style="text-indent: 2em">您好!</p>
				<p style="text-indent: 2em">
				  非常欢迎您参与龙湖·三千云锦1号地交付活动!为了保障您的现场看房体验，交付活动将实行预约方式，分时间段接待办理。请您根据自己时间安排进行预约。
				</p>
				<p>相关温馨提示如下:</p>
				<p>
				  1、交付活动时间：2024年12月30日-2025年1月1日，9:30-17:00；
				</p>
				<p>2、已约满时间段不会再显示，交付活动名额有限，先到先得；</p>
  
				<p>3、认证方式：业主本人姓名、身份证后六位、联系方式；</p>
  
				<p>4、报名通道开启时间：12月28日10:00；</p>
				<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;报名通道结束时间：12月29日12:00；</p>
				<p>5、活动签到地点：成都市龙湖·三千云锦1号地北门；</p>
				<p>6、系统需提示“尊敬的业主，恭喜您活动报名成功”字样，视为报名成功。（同一房源的产权共有人无法重复报名，多户置业者也无法重复报名）请将预约成功页面截屏留存；</p>
				<p>7、需要携带资料：购房合同，身份证原件；</p>
				<!-- <p>7、需要携带资料：</p>
				<p style="text-indent: 2em">①购房全款收据或购房首付款收据；</p>
				<p style="text-indent: 2em">
				  ②《商品房买卖合同》及补充协议原件；
				</p>
				<p style="text-indent: 2em">
				  ③权属登记申请有效证件：业主有效身份证件（身份证、军官证、护照、户口港澳台通行证等）；
				</p>
				<p>备注：</p>
				<p style="text-indent: 2em">
				  ①外籍人士、港澳台同胞另需提供2寸白底彩照1张；
				</p>
				<p style="text-indent: 2em">
				  ②购房人为未成年：监护人与被监护人户口本及医学出生证明原件或派出所开具的监护证明原件；
				</p>
				<p style="text-indent: 2em">
				  ③购房人为公司：应由公司法定代表人前来办理交接手续，同时需提供最新年检的营业执照副本、单位公章、法定代表人身份证或护照；由公司其他人员来接房的，需提交盖有公章的接房委托书及受托人的身份证或护照。前述证件复印件均需加盖公章。；
				</p>
				<p>
				  如业主本人不能亲临现场办理手续，须委托他人办理。经办人除需携带上述资料外，还需带上经公证处公证的《授权委托书》原件（受托人有转委托权）及受托人身份证原件。<br />
				  若房屋为多人共有，请全体业主同时到场，并参照上述内容携带相关资料。
				</p> -->
				<p>8、如有疑问可致电您的社区运营官：</p>
				<p>
				  刘佳贤：
				  <span
					style="color: royalblue"
					@click="copyText('180307905641')"
					>180307905641</span
				  >
				</p>
				<!-- <p>
				  汪家新：
				  <span
					style="color: royalblue"
					@click="copyText('17780025807')"
					>17780025807</span
				  >
				</p> -->
				<p style="height: 30rpx"></p>
			  </scroll-view>
			</view>
		  </view>
		  <view class="flex-1 mt-10 flex-center">
			<tm-button
			  :linear-color="['#ffd700', '#ffa500']"
			  linear="bottom"
			  :round="10"
			  :margin="[0, 0]"
			  fontColor="white"
			  form-type="submit"
			  :disabled="time != 0"
			  :label="`${time != 0 ? time : ''}完成阅读`"
			  @click="showTips = false"
			></tm-button>
		  </view>
		</tm-modal>
		<tm-modal
		  transprent
		  hideCancel
		  :width="720"
		  :height="1200"
		  :overlayClick="false"
		  splitBtn
		  content="主体内容哦"
		  v-model:show="showStart"
		>
		  <view class="tipsCss">
			<view class="tipsContent">
			  <view style="display: flex; flex-direction: row; align-items: end">
				<h2>温馨提示</h2>
				&nbsp;
				<p>WARM PROMPT</p>
			  </view>
			  <tm-divider realColor color="black"></tm-divider>
			  <div
				style="
				  display: flex;
				  justify-content: center;
				  align-items: center;
				  height: 100%;
				"
			  >
				报名通道将于12月27日上午10:00开启
			  </div>
			</view>
		  </view>
		</tm-modal>
		<tm-message
		  ref="msg"
		  :width="500"
		  :height="0"
		  :lines="5"
		  @click="closeMsg"
		  @updateClick="updateClick"
		></tm-message>
	  </view>
	</tm-app>
  </template>
  
  <script lang="ts" setup>
  import { ref, getCurrentInstance, computed, inject } from "vue";
  import tmApp from "@/tmui/components/tm-app/tm-app.vue";
  import tmButton from "@/tmui/components/tm-button/tm-button.vue";
  import tmMessage from "@/tmui/components/tm-message/tm-message.vue";
  import tmInput from "@/tmui/components/tm-input/tm-input.vue";
  import tmDivider from "@/tmui/components/tm-divider/tm-divider.vue";
  import tmForm from "@/tmui/components/tm-form/tm-form.vue";
  import * as dayjs from "@/tmui/tool/dayjs/esm/index";
  import { onMounted } from "vue";
  import { request } from "@/api/index";
  import { ResultEnum } from "@/enums/httpEnum";
  const DayJs = dayjs.default;
  // const today = DayJs().format('YYYY-MM-DD')
  const proxy = getCurrentInstance()?.proxy ?? null;
  const form = ref<InstanceType<typeof tmForm> | null>(null);
  const bgStyle =
	"background-image: linear-gradient(to right, #bb341f,#de6e2f,#f87f3d,#fbe1a3);";
  
  const body = "三千云锦1";
  const startTime = "2023-12-27T10:00:00";
  const isStartType = true;
  const loginForm = ref<Object | any>({
	owner_name: "",
	owner_id_number: "",
	owner_phone: "",
	date: "",
	tId: "",
	owner_number: null,
	project_name: body,
  });
  const showTips = ref(false);
  const formType = ref(0);
  const app = ref<InstanceType<typeof tmApp> | null>(null);
  const msg = ref<InstanceType<typeof tmMessage> | null>(null);
  
  const dateProps = {
	text: "date",
	value: "date",
  };
  const timeProps = {
	text: "sign_on_time",
	value: "id",
  };
  
  const showStart = ref(false);
  //判断是否已到预约时间
  
  const confirm = (e) => {
	if (e.isPass) {
	  const com = {
		owner_name: loginForm.value.owner_name,
		owner_phone: loginForm.value.owner_phone,
		owner_id_number: loginForm.value.owner_id_number,
		project_name: loginForm.value.project_name,
	  };
	  try {
		msg.value?.show({ model: "load" });
		request({
		  url: "/user/authentication/",
		  method: "post",
		  data: com,
		  header: {
			"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
		  },
		}).then((res) => {
		  if (res.code == ResultEnum.SUCCESS) {
			// setTimeout(() => {
			msg.value?.show({
			  model: "success",
			  text: "验证成功",
			  hideClose: true,
			});
			formType.value = 1;
			return;
			// }, 1000);
		  } else if (res.code == 4201) {
			// `尊敬的龙湖三千云锦1号地项目业主，您或您的亲人已经预约过本次活动,预约时间: <br>${res.else_data[0].sign_on_date} ${res.else_data[0].sign_on_time},如有疑问可致电您的社区运营官甘雪梅：18190698547，温振芝：18190692034`
			msg.value?.show({
			  model: "info",
			  text: `${res.error_msg}<br>预约房号: <br>${res.data[0].room_number}<br>预约时间: <br>${res.data[0].sign_on_date} ${res.data[0].sign_on_time}`,
			  duration: 300000,
			  hideUpdate: false,
			});
			// msg.value?.show({
			//   model: "info",
			//   text: res.error_msg,
			//   duration: 300000,
			//   hideUpdate: false,
			// });
		  } else {
			msg.value?.show({
			  model: "info",
			  text: res.error_msg,
			  duration: 300000,
			});
			return;
		  }
		});
	  } catch (error) {
		// setTimeout(() => {
		msg.value?.show({ model: "error", text: "错误", hideClose: true });
		// }, 2000);
	  }
	}
  };
  
  const closeMsg = () => {
	msg.value?.hide();
  };
  const updateClick = () => {
	formType.value = 2;
	msg.value?.hide();
  };
  
  const dateChange = () => {
	loginForm.value.tId = "";
	getDateTime();
  };
  
  const nowDateTime = ref("");
  const TimeChange = (e) => {
	nowDateTime.value = loginForm.value.date + " " + e.sign_on_time;
  };
  
  const time = ref(10);
  onMounted(() => {
	getDateTime();
	// timeLock()
	// showTips.value = true
	 倒计时();
  });
  
  function 倒计时() {
	isTime();
  }
  function calculateSecondsUntil(targetTime: any) {
	var currentTime: any = new Date();
	var targetDateTime: any = new Date(targetTime);
	var timeDiffInSeconds = Math.floor((targetDateTime - currentTime) / 1000);
  
	return timeDiffInSeconds;
  }
  function isTime() {
	const mm = calculateSecondsUntil(startTime);
	if (mm > 0 && isStartType) {
	  setTimeout(() => {
		倒计时();
	  }, 1000);
	  showStart.value = true;
	  return;
	}
	showStart.value = false;
	showTips.value = true;
	timeLock();
  }
  
  const subConfirm = (e) => {
	if (e.isPass) {
	  msg.value?.show({ model: "load" });
	  const com = {
		sign_on_id: loginForm.value.tId.split(",")[0],
		sign_on_time_id: loginForm.value.tId.split(",")[1],
		owner_name: loginForm.value.owner_name,
		owner_phone: loginForm.value.owner_phone,
		owner_id_number: loginForm.value.owner_id_number,
		project_name: loginForm.value.project_name,
		owner_number: loginForm.value.owner_number,
	  };
	  try {
		if (formType.value == 1) {
		  request({
			url: "/user/reservation/",
			method: "post",
			data: com,
			header: {
			  "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			},
		  }).then((res) => {
			getDateTime();
			if (res.code == ResultEnum.ODSUCCESS) {
			  // setTimeout(() => {
			  // msg.value?.show({ model: 'success', text: `尊敬的芳树晴川项目业主，恭喜您已成功预约本次集中交房，请您于：<br>${res.data.sign_on_date} ${res.data.sign_on_time}点前，前往都江堰市青城山镇大观社区10组31号龙湖.芳树晴川项目进行签到。`, duration: 300000, hideUpdate: false })
			  // msg.value?.show({ model: 'success', text: `尊敬的业主大大，恭喜您预约成功`, duration: 300000, hideUpdate: false })
			  msg.value?.show({
				model: "success",
				text: `${res.error_msg}<br>预约房号: <br>${res.else_data[0].room_number}<br>预约时间: <br>${res.else_data[0].sign_on_date} ${res.else_data[0].sign_on_time}`,
				duration: 300000,
				hideUpdate: false,
			  });
			  return;
			  // }, 1000);
			} else if (res.code == 4201) {
			  msg.value?.show({
				model: "info",
				text: `${res.error_msg}<br>预约房号: <br>${res.else_data[0].room_number}<br>预约时间: <br>${res.else_data[0].sign_on_date} ${res.else_data[0].sign_on_time}`,
				duration: 300000,
				hideUpdate: false,
			  });
			  // msg.value?.show({ model: 'info', text: '尊敬的业主大大，您或您的亲人已经预约过本次活动，如需修改预约时间段可点击下方修改按钮后修改，如有疑问可致电您的社区运营官杨旒：19950218389', duration: 300000, hideUpdate: false })
			} else {
			  msg.value?.show({
				model: "info",
				text: res.error_msg,
				duration: 300000,
			  });
			  return;
			}
		  });
		} else {
		  request({
			url: "/user/update_reservation/",
			method: "post",
			data: com,
			header: {
			  "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			},
		  }).then((res) => {
			getDateTime();
			if (res.code == 2002) {
			  // setTimeout(() => {
			  // msg.value?.show({ model: 'success', text: `尊敬的芳树晴川项目业主，恭喜您已成功修改本次集中交房，请您于：<br>${nowDateTime.value}点前，前往都江堰市青城山镇大观社区10组31号龙湖.芳树晴川项目进行签到。`, duration: 300000 })
			  // msg.value?.show({ model: 'success', text: `尊敬的业主大大，恭喜您预约成功`, duration: 300000, hideUpdate: false })
			  msg.value?.show({
				model: "success",
				text: `${res.error_msg}<br>预约房号: <br>${res.else_data[0].room_number}<br>预约时间: <br>${res.else_data[0].sign_on_date} ${res.else_data[0].sign_on_time}`,
				duration: 300000,
				hideUpdate: false,
			  });
			  return;
			  // }, 1000);
			} else {
			  msg.value?.show({
				model: "info",
				text: res.error_msg,
				duration: 300000,
			  });
			  return;
			}
		  });
		}
	  } catch (error) {
		// setTimeout(() => {
		msg.value?.show({ model: "error", text: "错误", hideClose: true });
		// }, 2000);
	  }
	}
  };
  
  const timeLock = () => {
	setTimeout(() => {
	  if (time.value != 0) {
		time.value--;
		timeLock();
	  }
	}, 1000);
  };
  
  const optionsDate: any = [];
  const optionsTime: any = ref({});
  const getDateTime = () => {
	request({
	  url: `/user/reservation/?project_name=${body}`,
	  method: "get",
	}).then((res) => {
	  if (res.code == ResultEnum.SUCCESS) {
		let com = res.data;
		for (const date in res.data) {
		  if (optionsDate.length != Object.keys(res.data).length) {
			//判断是否是当天的次日，是就不显示
			// if (!isNextDayOrBefore(date)) {
			optionsDate.push({ date: date });
			// }
		  }
		  com[date].forEach((obj) => {
			obj.id = `${obj.sign_on_id},${obj.sign_on_time_id}`;
		  });
		}
		for (const date in res.data) {
		  com[date] = com[date].filter((obj) => obj.sign_on_number !== 0);
		}
		optionsTime.value = com;
	  } else {
		msg.value?.show({ model: "error", text: res.error_msg, hideClose: true });
	  }
	});
  };
  
  // function isNextDayOrBefore(date1, date2) {
  // 	const d1 = DayJs(date1);
  // 	const d2 = DayJs(date2);
  
  // 	// 获取两个日期的差值（天数）
  // 	const dayDifference = d2.diff(d1, 'day');
  
  // 	// 判断 dayDifference 是否为 1 或者更少
  // 	return dayDifference > 1;
  // }
  function isNextDayOrBefore(date2) {
	// 使用 Day.js 解析 date1 和 date2
	const d1 = DayJs(); // 当前时间
	const d2 = DayJs(date2, "YYYY-MM-DD"); // 需要判断的日期
  
	// 获取 date2 前一天的 18:00
	const previousDay = d2.subtract(1, "day").hour(18).minute(0).second(0);
  
	// 判断 date1 是否已经过了 date2 前一天的 18:00
	return d1.isAfter(previousDay);
  }
  
  function copyText(text) {
	uni.setClipboardData({
	  data: text,
	  success: () => {
		uni.showToast({
		  title: "复制成功",
		  icon: "success",
		  duration: 2000,
		});
	  },
	  fail: () => {
		uni.showToast({
		  title: "复制失败",
		  icon: "none",
		  duration: 2000,
		});
	  },
	});
  }
  </script>
  <style>
  .bgImg {
	background-image: url("@/static/bgImg.webp");
	background-size: 100% auto;
	background-position: top;
	background-repeat: no-repeat;
	width: 100%;
	height: 600rpx;
  }
  
  .bgImg2 {
	background-image: url("@/static/bgImg2.jpg");
	background-size: 100% auto;
	background-position: top;
	background-repeat: no-repeat;
	max-width: 900rpx;
	width: 100%;
	height: 900rpx;
	position: fixed;
	bottom: 0;
	/* z-index: 0; */
  }
  
  .tipsCss {
	background-color: white;
	height: 1000rpx;
	border-radius: 20rpx;
	padding: 10rpx;
  }
  
  .tipsContent {
	overflow: hidden;
	width: 100%;
	height: 100%;
	border: 1px solid #000;
	border-radius: 20rpx;
	padding: 50rpx 40rpx 50rpx 40rpx;
  }
  
  /* :deep(.noNvueBorder) {
	  .noNvueBorder {
		  border-radius: 5px;
		  border: 0.0625rem solid white !important;
	  }
  } */
  
  /* :deep(.uni-input-placeholder) {
	  color: black !important;
  }
  
  :deep(.e-select) {
	  border: 0.0625rem solid #F5BD41 !important;
	  color: black !important;
  }
  
  :deep(.e-select__input-text) {
	  color: black !important;
  
  }
  
  :deep(.uni-input-input) {
	  color: black !important;
  } */
  </style>
  